<template>
  <el-row>
    <ImportExcelModal :visible.sync="visible" fileType="fwOrderTemp" title="导单"
                      downLoadUrl="/static/excel/直营服务订单导入模版.xlsx">
      <div slot="tips" class="col-xs-12 m--margin-top-10">
        <p class="font-red text-center">
          由于上传文件转换为订单需要时间处理，上传后文件处理情况请在处理结果中查看，文件处理成功后订单将进入暂存单列表。
        </p>
      </div>
    </ImportExcelModal>

    <ImportResult :visible.sync="resultVisible"
                  url="/ms-common-excelupload/excel/getImportData?tempalateType=fwOrderTemp"></ImportResult>
    <el-col :span="24">
      <Portlet title="服务暂存单">
        <el-form @keyup.enter.native="searchFunc(search)" ref="searchForm" class="el-form-col search-form"
                 :model="search">
          <el-row :gutter="15">
            <el-col :lg="4" :md="6">
              <el-form-item prop="orderNo">
                <el-input v-model="search.orderNo" @keyup.enter.native.stop type="textarea" :rows="4"
                          placeholder="订单号  (支持多单查询，用英文逗号分隔)"
                          clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item prop="outNo">
                <el-input v-model="search.outNo" @keyup.enter.native.stop type="textarea" :rows="4"
                          placeholder="来源单号  (支持多单查询，用英文逗号分隔)"
                          clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item prop="consigneName">
                <el-input v-model="search.consigneName" placeholder="客户姓名" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6" class="hidden-lg-only hidden-xl-only">
              <el-form-item>
                <el-row class="search-btns" :gutter="5">
                  <el-col :span="8">
                    <el-button type="primary" :loading="searchLoading" plain native-type="submit" @click.prevent="searchFunc(search)"><span>搜索</span>
                    </el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button type="info" plain @click="isOpen = !isOpen">{{ isOpen ? '收起' : '展开' }}</el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button @click="resetFields" plain>重置</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item prop="consignePhone">
                <el-input v-model="search.consignePhone" placeholder="客户电话" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item prop="isStorage">
                <el-select v-model="search.isStorage" clearable placeholder="是否仓储">
                  <el-option label="否" :value="0"></el-option>
                  <el-option label="是" :value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6" class="hidden-md-only hidden-sm-only">
              <el-form-item>
                <el-row class="search-btns" :gutter="5">
                  <el-col :span="8">
                    <el-button type="primary" :loading="searchLoading" plain native-type="submit" @click.prevent="searchFunc(search)"><span>搜索</span>
                    </el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button type="info" plain @click="isOpen = !isOpen">{{ isOpen ? '收起' : '展开' }}</el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button @click="resetFields" plain>重置</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item prop="storageTypeCode">
                <el-select v-model="search.storageTypeCode" clearable placeholder="仓库类型">
                  <el-option
                    v-for="item in cargoSourceTypes"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item prop="businessNo">
                <el-select v-model="search.businessNo" clearable placeholder="业务类型">
                  <el-option
                    v-for="item in businessArr"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :lg="4" :md="6">
              <el-form-item prop="outSourceWarehouse">
                <el-input v-model="search.outSourceWarehouse" placeholder="订单来源"
                          clearable></el-input>
              </el-form-item>
            </el-col>

            <el-col :lg="4" :md="6">
              <el-form-item prop="serviceNo">
                <el-select v-model="search.serviceNo" clearable placeholder="服务类型">
                  <el-option
                    v-for="item in serviceArr"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-collapse-transition>
            <div v-show="isOpen">
              <el-row :gutter="15">

                <el-col :lg="4" :md="6">
                  <el-form-item prop="addressArr">
                    <CascadeAddress v-model="search.addressArr" placeholder="客户地址" :level="3" changeOnSelect/>
                  </el-form-item>
                </el-col>

                <el-col :lg="4" :md="6">
                  <el-form-item prop="founderUserName">
                    <el-input v-model="search.founderUserName" placeholder="导入人"></el-input>
                  </el-form-item>
                </el-col>

                <el-col :lg="4" :md="6">
                  <el-form-item prop="foundStartDate">
                    <el-date-picker type="date"
                                    placeholder="导入开始时间"
                                    v-model="search.foundStartDate"
                                    value-format="yyyy-MM-dd"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>

                <el-col :lg="4" :md="6">
                  <el-form-item prop="foundEndDate">
                    <el-date-picker type="date"
                                    placeholder="导入结束时间"
                                    v-model="search.foundEndDate"
                                    value-format="yyyy-MM-dd"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-collapse-transition>

        </el-form>
      </Portlet>
    </el-col>
    <el-col :span="24">
      <BasicTable
        ref="BasicTable"
        url="/ms-warehouse-order/orderTemp/getFwOrderTempImportList"
        @selection-change="setRows"
        :columns="columns">
        <template slot="preColumn">
          <el-table-column prop="orderNo" fixed="left" width="170px" align="center" label="订单号">
            <template slot-scope="scope">
              <a href="javascript: void (0);" @click.prevent="show(scope.row)">
                {{ scope.row.orderNo }}
              </a>
            </template>
          </el-table-column>
        </template>

        <template slot="column">
          <el-table-column fixed="right" align="center" width="80px" label="操作">
            <template slot-scope="scope">
              <template>
                <el-button
                  size="mini"
                  type="text"
                  @click="show(scope.row)"
                >
                  确定转正
                </el-button>
              </template>

            </template>
          </el-table-column>
        </template>

        <template v-if="tabIndex == 1" slot="buttons">
          <el-button type="primary" @click.prevent="visible = true">导入服务订单</el-button>
          <el-button type="primary" @click.prevent="resultVisible = true">导入结果</el-button>
          <el-button @click.prevent="submit()" type="warning">批量提交</el-button>
          <el-button @click.prevent="remove" type="danger">移除订单</el-button>
        </template>

        <span class="font-red"  v-if="tabIndex == 2" slot="tips">
          由于上传文件转换为订单需要时间处理，上传后文件处理情况请在处理结果中查看，文件处理成功后订单将进入暂存单列表。
        </span>
      </BasicTable>
    </el-col>
  </el-row>
</template>
<script>
import ImportExcelModal from '@/views/oms/ImportExcelModal'
import ImportResult from '@/views/business/ImportResult'
import {copy, alert, dotData, confirm, arrayColumn} from '@/utils'
import {urlPrefix} from '@/config'
import {decimalNumFilter, unixTimestampFilter, filterDataBaseDictionary, isTrue} from '@/filters'
import {getCargoSourceType, getOmsBusinessList, getServiceType, getSubDictListOfParentCode} from '@/utils/selectOptions'
import {getLoginUser} from '@/utils/ajax'
import StompJs from '@/utils/StompJs'
export default {
  name: 'orderTempService',
  components: {
    ImportExcelModal,
    ImportResult
  },
  filters: {
    decimalNumFilter,
    filterDataBaseDictionary
  },
  data() {
    return {
      tabIndex: 1,
      searchLoading: false,
      search: {
        orderNo: '',
        outNo: '',
        storageTypeCode: '',
        cargoOwner: '',
        consigneName: '',
        consignePhone: '',
        founderUserName: '',
        foundStartDate: '',
        foundEndDate: '',
        businessNo: '',
        serviceNo: '',
        storageType: '',
        isStorage: '',
        outSourceWarehouse: '',
        addressArr: []
      },
      customParams: {
        pageSize: 50,
        pageNum: 1
      },
      isOpen: false,
      resultVisible: false,
      columns: [
        {
          label: '订单来源',
          data: 'outSourceWarehouse'
        },
        {
          label: '推单单号',
          data: 'outNo'
        },
        {
          label: '是否仓储',
          data: 'isStorage',
          render: (data, full) => {
            return isTrue(data)
          }
        },
        {
          label: '仓储类型',
          data: 'storageType'
        },
        {
          label: '业务类型',
          data: 'business'
        },
        {
          label: '服务类型',
          data: 'service'
        },
        {
          label: '商家名称',
          data: 'cargoOwner'
        },
        {
          label: '客户姓名',
          data: 'consigneName'
        },
        {
          label: '客户电话',
          data: 'consignePhone'
        },
        {
          label: '客服地址',
          data: 'province+city+district',
          render(data, full) {
            return `${full.province} ${full.city} ${full.district}`
          },
          width: 200
        },
        {
          label: '商品总数',
          data: 'productNum'
        },
        {
          label: '总包件',
          data: 'totalPackage'
        },
        {
          label: '总体积(m³)',
          data: 'totalVolume'
        },
        {
          label: '总重量(kg)',
          data: 'totalWeight'
        },
        {
          label: '导入人',
          data: 'founderUserName'
        },
        {
          label: '导入时间',
          data: 'foundDate',
          render(data, type, full, meta) {
            return unixTimestampFilter(data)
          },
          width: 140
        }
      ],
      cargoSourceTypes: [],
      businessArr: [],
      orderSourceArr: [],
      serviceArr: [],
      urlPrefix,
      visible: false,
      rows: [],
      subOrderFinish: '' // 一个消息订阅
    }
  },
  created() {
    getCargoSourceType().then(arr => {
      this.cargoSourceTypes = arr
    })
    // 业务类型
    getOmsBusinessList().then(arr => {
      this.businessArr = arr
    })
    getServiceType().then(arr => {
      this.serviceArr = arr
    })
    getSubDictListOfParentCode('CHORDERSOURCE').then(arr => {
      this.orderSourceArr = arr
    })
    let s1 = new StompJs()
    let userId = getLoginUser('id')
    s1.subscribe('/topic/' + userId + 'orderFinish', (message) => {
      this.refresh()
    }).then(sub => {
      this.subOrderFinish = sub
    })
  },
  destroyed() {
    if (this.subOrderFinish) {
      this.subOrderFinish.unsubscribe()
    }
  },
  methods: {
    searchFunc(search) {
      const basicTable = this.$refs.BasicTable
      if (basicTable) {
        let params = copy(search)
        params.provinceNo = dotData(params, 'addressArr[0]') || ''
        params.cityNo = dotData(params, 'addressArr[1]') || ''
        params.districtNo = dotData(params, 'addressArr[2]') || ''
        delete params.addressArr
        this.searchLoading = true
        basicTable.search(params).finally(_ => {
          this.searchLoading = false
        })
      }
    },
    // 重置表单
    resetFields() {
      const searchForm = this.$refs.searchForm
      if (searchForm) {
        searchForm.resetFields()
      }
    },
    // 表格刷新
    refresh() {
      this.searchFunc(this.search)
    },
    // 选中的值
    setRows(rows) {
      this.rows = rows
    },
    show(data) {
      this.$router.push({path: '/ss-oms/order/temp-service-show/' + data.id})
    },
    submit(arr) {
      if (arr === undefined) {
        arr = this.rows
      } else {
        arr = [arr]
      }
      if (Array.isArray(arr) && arr.length > 0) {
        confirm(`
          <p>是否确认提交被选中的${arr.length}单服务暂存单？</p>
          <p>请确认服务暂存单信息正确，提交后您可以在入库单列表查看这些订单。</p>
        `, '提交服务订单', {
          type: 'warning',
          confirmButtonLoading: true,
          dangerouslyUseHTMLString: true,
          confirmCallBack: ({close, confirmButtonLoadingClose}) => {
            this.$ajax.post('/ms-warehouse-order/service-order-controller/service-order-positive', arrayColumn(arr, 'id')).then(response => {
              const success = dotData(response, 'success')
              if (success) {
                close().then(_ => {
                  confirm(`您提交的${arr.length}单服务暂存单其中${dotData(response, 'data')}单提交成功，${arr.length - dotData(response, 'data')}单提交失败请在服务暂存单详情中核对订单信息，确认无误后再次提交`, undefined, {
                    type: 'success'
                  })
                  confirmButtonLoadingClose()
                }).finally(_ => {
                  this.refresh()
                })
              } else {
                confirmButtonLoadingClose()
              }
            }).catch(_ => {
              confirmButtonLoadingClose()
            })
          }
        })
      } else {
        alert('请选择数据')
      }
    },
    remove() {
      let data = this.rows
      if (Array.isArray(data) && data.length > 0) {
        confirm(`
          <p>是否确认移除被选中的${data.length}单服务暂存单？</p>
          <p>移除后不可恢复只能重新录单或导入。</p>
        `, '移除服务订单', {
          type: 'warning',
          confirmButtonLoading: true,
          dangerouslyUseHTMLString: true,
          confirmCallBack: ({close, confirmButtonLoadingClose}) => {
            this.$ajax.post('/ms-warehouse-order/orderTemp/removeOrderTemp', arrayColumn(data, 'id')).then(response => {
              const success = dotData(response, 'success')
              if (success) {
                close().then(_ => {
                  confirm(`成功移除${data.length}单服务暂存单`, undefined, {
                    type: 'success'
                  }).finally(_ => {
                    this.refresh()
                  })
                  confirmButtonLoadingClose()
                })
              } else {
                confirmButtonLoadingClose()
              }
            }).catch(_ => {
              confirmButtonLoadingClose()
            })
          }
        })
      } else {
        alert('请选择数据')
      }
    }
  }
}
</script>
